package cn.socialcredits.activity.business

import java.time.LocalDateTime
import javax.inject.{Inject, Singleton}

import cn.socialcredits.activity.data.domain.RegisterActivity
import cn.socialcredits.activity.data.model.{Activity, ActivityRegistration}
import cn.socialcredits.activity.data.repo.{ActivityRegistrationRepo, ActivityRepo}
import org.apache.commons.lang3.StringUtils
import reactivemongo.bson.BSONObjectID

import scala.concurrent.Future

@Singleton
class ActivityService @Inject()(activityRepo: ActivityRepo,
                                activityRegistrationRepo: ActivityRegistrationRepo) {

  import play.api.libs.concurrent.Execution.Implicits.defaultContext

  def registerActivity(payload: RegisterActivity) = {
    require(StringUtils.isNoneBlank(payload.name), "请填写姓名")
    require(StringUtils.isNoneBlank(payload.phone), "请填写手机号")
    require(StringUtils.isNoneBlank(payload.corporation), "请填写公司")

    val registration = ActivityRegistration(
      BSONObjectID.generate,
      BSONObjectID(payload.activity),
      payload.name,
      payload.phone,
      payload.corporation,
      payload.job,
      LocalDateTime.now())
    activityRegistrationRepo.insert(registration)
  }

  def findRegistrationOneById(id: BSONObjectID): Future[Option[(ActivityRegistration, Activity)]] = {
    activityRegistrationRepo.findOneById(id).flatMap {
      case Some(registration) =>
        activityRepo.findOneById(registration.activityId).map {
          case Some(activity) => Some((registration, activity))
          case None => None
        }

      case None =>
        Future.successful(None)
    }
  }

  def findOneById(id: BSONObjectID) =
    activityRepo.findOneById(id)
}
